import React, { useState, useEffect } from 'react';
import { obj_str, obj_float, useCmd, is_empty, obj_empty, loc } from 'sui';
import { Bind } from 'manage/station/ctl';
import { save_auto, reload_mt } from '../cmd';

const BindMt = ({ cur, hreturn, mt, alert }) => {
    const [main_user, mainUser] = useState([]);
    const [checked, setChecked] = useState([]);
    const umd = useCmd();

    useEffect(() => {
        reload_mt(null, v => umd.setValue(v));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => mainUser(mt), [mt]);

    const remove = (v) => {
        umd.startWait();

        const val = [];
        const set = new Set();

        if (umd.value) {
            umd.value.forEach(d => {
                if (d === v) {
                    return;
                }

                set.add(d);
            });
        }

        main_user.forEach(d => {
            if (set.has(d.sn)) {
                val.push({
                    sn: obj_str(d, "sn"),
                    name: obj_str(d, "name"),
                    dw: obj_float(d, "name"),
                    std: obj_float(d, "std"),
                    sub: obj_float(d, "sub"),
                });
            }
        });

        save_auto({ batch: val },
            () => {
                setChecked([]);
                reload_mt(umd.endWait, v => umd.setValue(v));
            },
            () => umd.setErr());
    };

    const addUser = () => {
        if (obj_empty(cur) || is_empty(checked)) {
            return;
        }

        umd.startWait();

        const set = new Set();
        checked.forEach(d => set.add(d));

        const val = [];

        if (umd.value) {
            umd.value.forEach(d => set.add(d));
        }

        main_user.forEach(d => {
            if (set.has(d.sn)) {
                val.push({
                    sn: obj_str(d, "sn"),
                    name: obj_str(d, "name"),
                    dw: obj_float(d, "name"),
                    std: obj_float(d, "std"),
                    sub: obj_float(d, "sub"),
                });
            }
        });

        if (val.length > 7) {
            umd.setErr(loc("l_870"));
            return;
        }

        save_auto({ batch: val },
            () => {
                setChecked([]);
                reload_mt(umd.endWait, v => umd.setValue(v));
            },
            () => umd.setErr());
    };

    return <Bind umd={umd} cur={cur} hreturn={hreturn} hadd={addUser} checked={checked} setChecked={setChecked} title={loc("l_488")}
                 hremove={remove} main={main_user} setMain={mainUser} alert={alert}/>;
};

export {BindMt};
